package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFAnchor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author with葡萄成熟时
 * @version 1.0
 */
@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * @description 营业额统计接口
     * @author Wait葡萄成熟时
     * @date 下午11:39 2024/11/24
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList();

        dateList.add(begin);

        while (!begin.equals(end)) {
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }


        List<Double> turnoverSum = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //查询date日期对应的营业额数据，营业额是指：状态为“已完成"的订单金额合计,详细开始时间与结束时间
            LocalDateTime beginDateTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endDateTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //select sum(amornt)from orders where order_time>beginTime and order_time<endTime and status=5

            Map map = new HashMap<>();
            map.put("begin", beginDateTime);
            map.put("end", endDateTime);
            map.put("status", Orders.COMPLETED);

            Double sum = orderMapper.sumByMap(map);
            //判断营业额是否存在，不存在就变为0
            if (sum == null) {
                sum = (double) 0;
            }
            turnoverSum.add(sum);
        }
        //自定义的工具类转为String类型
        String date = StringUtils.join(dateList, ",");
        String turnover = StringUtils.join(turnoverSum, ",");

        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        turnoverReportVO.setTurnoverList(turnover);
        turnoverReportVO.setDateList(date);

        return turnoverReportVO;
    }

    /**
     * @description 用户统计接口
     * @author Wait葡萄成熟时
     * @date 下午11:54 2024/11/24
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList();

        dateList.add(begin);

        while (!begin.equals(end)) {
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }


        //存放每天的新增用户数量select count（id）from user where create_time<？and create_time>？
        List<Integer> newUserList = new ArrayList<>();
        //l存放每天的总用户数量select count（id）from user where create_time<？
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate localDate : dateList) {
            //查询date日期对应的营业额数据，营业额是指：状态为“已完成"的订单金额合计,详细开始时间与结束时间
            LocalDateTime beginDateTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endDateTime = LocalDateTime.of(localDate, LocalTime.MAX);

            //总的人数
            Map map = new HashMap<>();
            map.put("end", endDateTime);
            Integer countTotal = userMapper.countByMap(map);
            totalUserList.add(countTotal);
            //新增的人数
            map.put("begin", beginDateTime);
            Integer countNew = userMapper.countByMap(map);
            newUserList.add(countNew);

        }
        //自定义的工具类转为String类型
        String date = StringUtils.join(dateList, ",");
        String totalUserList1 = StringUtils.join(totalUserList, ",");
        String newUserList1 = StringUtils.join(newUserList, ",");

        UserReportVO userReportVO = new UserReportVO();
        userReportVO.setDateList(date);
        userReportVO.setTotalUserList(totalUserList1);
        userReportVO.setNewUserList(newUserList1);
        return userReportVO;
    }

    /**
     * @description 订单统计接口
     * @author Wait葡萄成熟时
     * @date 上午10:30 2024/11/25
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList();

        dateList.add(begin);

        while (!begin.equals(end)) {
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //存储每天总的订单数
        List<Integer> orderCountList = new ArrayList<>();
        //存储每天有效总的订单数
        List<Integer> validOrderCountList = new ArrayList<>();

        //总的订单数
        Integer sumOrderCount = 0;
        //总的有效的订单数
        Integer sumValidOrder = 0;

        for (LocalDate localDate : dateList) {
            //查询date日期对应的营业额数据，营业额是指：状态为“已完成"的订单金额合计,详细开始时间与结束时间
            LocalDateTime beginDateTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endDateTime = LocalDateTime.of(localDate, LocalTime.MAX);

            //变成map搞进去查询
            Map map = new HashMap<>();
            map.put("begin", beginDateTime);
            map.put("end", endDateTime);
            //每天的订单数
            Integer orderCount = orderMapper.countByOrder(map);
            orderCountList.add(orderCount);
            //每天有效订单
            map.put("status", Orders.COMPLETED);
            Integer validCount = orderMapper.countByOrder(map);
            validOrderCountList.add(validCount);

            //把每天的都加起来
            sumOrderCount = orderCount + sumOrderCount;
            sumValidOrder = validCount + sumValidOrder;
        }

        //计算全部的百分比
        Double orderCompletionRate = 0.0;
        if (sumOrderCount != null) {
            orderCompletionRate = sumValidOrder.doubleValue() / sumOrderCount;
        }

        //自定义的工具类转为String类型
        String date = StringUtils.join(dateList, ",");
        String orderCountList1 = StringUtils.join(orderCountList, ",");
        String validOrderCountList1 = StringUtils.join(validOrderCountList, ",");


        return new OrderReportVO(date, orderCountList1, validOrderCountList1, sumOrderCount, sumValidOrder, orderCompletionRate);

    }

    /**
     * @description 查询销量排名top10接口
     * @author Wait葡萄成熟时
     * @date 下午12:06 2024/11/25
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //处理数据
        LocalDateTime beginDateTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endDateTime = LocalDateTime.of(end, LocalTime.MAX);

        //变成map搞进去查询
        Map map = new HashMap<>();
        map.put("begin", beginDateTime);
        map.put("end", endDateTime);
        map.put("status", Orders.COMPLETED);

        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop(map);


        List<String> names = new ArrayList();
        List<Integer> numbers = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO : goodsSalesDTOList) {

            names.add(goodsSalesDTO.getName());
            numbers.add(goodsSalesDTO.getNumber());
        }

        //自定义的工具类转为String类型
        String name = StringUtils.join(names, ",");
        String number = StringUtils.join(numbers, ",");

        SalesTop10ReportVO salesTop10ReportVO = new SalesTop10ReportVO();
        salesTop10ReportVO.setNameList(name);
        salesTop10ReportVO.setNumberList(number);

        return salesTop10ReportVO;
    }

    @Override
    public void exportExsel(HttpServletResponse httpServletResponse) {
        //.查询数据库，获取营业数据---查询最近30天的运营数据
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);


        //查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(endDate, LocalTime.MAX));

        //2.通过POI将数据写入到ExceL文件中
        InputStream InputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");


        try {
            //基于模板文件创建一个新的ExceL文件
            XSSFWorkbook excel = new XSSFWorkbook(InputStream);
            //获取表格文件的Sheet页
            XSSFSheet sheet=excel.getSheet("Sheet1");
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间"+beginDate+"到"+endDate);

            //获得第4行
            XSSFRow row4 = sheet.getRow(3);
            row4.getCell(2).setCellValue(businessData.getTurnover());
            row4.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row4.getCell(6).setCellValue(businessData.getNewUsers());

            //获得第5行
            XSSFRow row5 = sheet.getRow(4);
            row5.getCell(2).setCellValue(businessData.getValidOrderCount());
            row5.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = endDate.plusDays(-i);
                //查询概览数据
                BusinessDataVO businessDataEveryDay = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));


                //获得某一行
                XSSFRow rowN= sheet.getRow(7+i);
                rowN.getCell(1).setCellValue(date.toString());
                rowN.getCell(2).setCellValue(businessDataEveryDay.getTurnover());
                rowN.getCell(3).setCellValue(businessDataEveryDay.getValidOrderCount());
                rowN.getCell(4).setCellValue(businessDataEveryDay.getOrderCompletionRate());
                rowN.getCell(5).setCellValue(businessDataEveryDay.getUnitPrice());
                rowN.getCell(6).setCellValue(businessDataEveryDay.getNewUsers());


            }



            //3.通过输出流将ExceL文件下载到客户端浏览器
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            excel.write(outputStream);





            outputStream.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
